﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System.ComponentModel;
using Windows.Application.Share;
using Windows.Infrastructure.Share.Security;

namespace Windows.Api.Share.Filter
{
    public class PrivilegeAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
    {
        //public ICurrentUser CurrentUser { get; set; }
        public PrivilegeAttribute(string[] licenses, bool isAlso = false)
        {
            Lincenses = licenses;
            IsAlso = isAlso;
        }
        /// <summary>
        /// 权限字符串，例如 system:user:view
        /// </summary>
        public string[] Lincenses { get; set; }
        /// <summary>
        /// true:and,false:or
        /// </summary>
        public bool IsAlso { get; set; }
        public Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item is AllowAnonymousAttribute))
                return Task.CompletedTask;

            ICurrentUser currentUser = (ICurrentUser)context.HttpContext.RequestServices.GetService(typeof(ICurrentUser))!;
            if (currentUser.IsAdmin)
                return Task.CompletedTask;

            if (IsAlso)
            {
                int count = 0;
                foreach (string license in Lincenses)
                {
                    if (currentUser.Licenses.Any(x => x == license))
                        count++;
                }
                if (Lincenses.Length < count)
                    throw new ApiException(ApiStatusEnum.Fail_UnAuthorized);
            }
            else
            {
                if (!currentUser.Licenses.Any(x => Lincenses.Contains(x)))
                    throw new ApiException(ApiStatusEnum.Fail_UnAuthorized);
            }
            return Task.CompletedTask;
        }
    }
}
